import api from './api'
import config from '../config'
const util = {
  //urlParams传入数组或者字符串，字符串时默认替换api第一个%s，数组依次替换%s
  async generateRquestUrl(module, name, urlParams) {
    if (api[module] && api[module][name]) {
      let url = api[module][name]
      if (urlParams) {
        if (typeof urlParams == 'string') {
          url = url.replace('%s', urlParams)
        }
        if (Array.isArray(urlParams)) {
          url = url.replace(/%s/g, function (match) {
            return urlParams.shift()
          })
        }
      }
      return config[module + 'Endpoint'] + url
    } else {
      throw new Error('api not defined in util/api.js')
    }
  },
  jsonToString(data) {
    let str = []
    for (let p in data) {
      if (Object.prototype.hasOwnProperty.call(data, p)) {
        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p]))
      }
    }
    return str.join('&')
  },
  async sleep(time) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
      }, time)
    })
  }
}

export default util
